package erciyuan.hoolai.com.jwtdemo2;

import android.util.Base64;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Administrator on 2018/4/13.
 */

public class DBWebSignature {

    public static String secret = "moca";//密匙
    public static String delimiter = ".";


    public static String gettoken(JSONObject header,JSONObject payload) throws InvalidKeyException, NoSuchAlgorithmException {

        String headerbase64=getheader(header);
        String payloadbase64=getpoyload(payload);
        String input = headerbase64+ delimiter + payloadbase64;
        String signstr=getsign(input);
        String token=headerbase64 + delimiter + payloadbase64 + delimiter + signstr;
        return token;
    }

    public static String getheader(JSONObject header){
        String headerSegment = base64str(header.toString());
        return headerSegment;
    }

    public static String getpoyload(JSONObject payload){
        String payloadSegment = base64str(payload.toString());
        return payloadSegment;

    }

    public static String getsign(String message) throws NoSuchAlgorithmException, InvalidKeyException {

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(),"HmacSHA256");
        sha256_HMAC.init(secret_key);
//        String sign=sha256_HMAC.doFinal(message.getBytes()).toString();
//        String signstr=base64str(sign);
        String hashs = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), android.util.Base64.NO_WRAP);

        return hashs;
    }


    public static String base64str(String str){
        return Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
    }

}
